//
//  HJHomeTableVC.swift
//  Weibo
//
//  Created by 韩佳 on 16/4/16.
//  Copyright © 2016年 ddg. All rights reserved.
//

import UIKit

class HJHomeTableVC: HJVisitorTableVC {

    override func viewDidLoad() {
        super.viewDidLoad()
        if userLogon == false{
            
        visitorView.VisitorView(nil, imgName: nil)
          return
        }
        setupUI()
        updateData()
    }
    let HMStatusCellId = "HMStatusCellId"
    func setupUI(){
        //设置组尾
        tableView.tableFooterView = pullupView
        
        tableView.registerClass(HJStatusCell.self, forCellReuseIdentifier: HMStatusCellId)
        //预估行高
        tableView.estimatedRowHeight = 200
        //自动行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //系统下拉刷新
//        self.refreshControl = UIRefreshControl()
//        self.refreshControl?.addTarget(self, action: "updateData", forControlEvents: UIControlEvents.ValueChanged)
        //自定义下拉刷新
        tableView.addSubview(hjRefreshControl)
        hjRefreshControl.addTarget(self, action: "updateData", forControlEvents: UIControlEvents.ValueChanged)
    }
    func updateData(){
        statusListViewModel.loadData(pullupView.isAnimating()) { (isSuccess) -> () in
            if isSuccess{
                self.tableView.reloadData()
            }else{
                print("请求数据失败")
            }
            self.endRefreshing()
        }

    }
    private func endRefreshing(){
        self.pullupView.stopAnimating()
        self.refreshControl?.endRefreshing()
        self.hjRefreshControl.endRefreshing()
    }
    private lazy var statusListViewModel:HJStatusListViewModel = HJStatusListViewModel()
    private lazy var pullupView: UIActivityIndicatorView = {
        let pullupView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        pullupView.color = UIColor.darkGrayColor()
//        pullupView.hidesWhenStopped = false
        return pullupView
    }()
    private lazy var hjRefreshControl:HJRefreshControl = HJRefreshControl()

}

extension HJHomeTableVC {
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusArray!.count - 1 && !pullupView.isAnimating() {
            pullupView.startAnimating()
            updateData()
        }
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusArray?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HMStatusCellId, forIndexPath: indexPath) as! HJStatusCell
        
        let statueViewModel = statusListViewModel.statusArray![indexPath.row]
        cell.statueViewModel = statueViewModel
        return cell
    }
}











